import { useRef, useState } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, DatePicker, Popconfirm, Spin, Table, TableProps, Upload, UploadFile } from 'antd';
import dayjs from 'dayjs';
import Saver from 'file-saver';
import { omit } from 'lodash-es';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import {
  proDataSewageDelete,
  proDataSewageDownloadTemplate,
  proDataSewageImport,
  proDataSewagePage
} from '@/services/bizApi/wushuishujujiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProDataSewageEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();
  const fileList = useRef<UploadFile[]>([]);
  const [selectedRows, setSelectedRows] = useState<React.Key[]>([]);
  const [spinning, setSpinning] = useState(false);

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      let query = {
        ...formData,
        ...id,
        rqBegin: formData.rq ? dayjs(formData.rq?.[0]).format('YYYY-MM-DD') : undefined,
        rqEnd: formData.rq ? dayjs(formData.rq?.[1]).format('YYYY-MM-DD') : undefined,
        page: current,
        size: pageSize
      };
      query = omit(query, 'rq');
      const res = await proDataSewagePage(query);

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  const handleImport = useRequest(
    async () => {
      setSpinning(true);
      const formData = new FormData();
      formData.append('file', fileList.current[0].originFileObj as File);

      await proDataSewageImport({} as ArgumentsType<typeof proDataSewageImport>[0], {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        data: formData,
        timeout: 60000
      }).finally(() => {
        setSpinning(false);
      });

      store.app?.message.success('导入成功');
      table.search.submit();
    },
    {
      manual: true
    }
  );

  const rowSelection: TableProps<BizObject>['rowSelection'] = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: BizObject[]) => {
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setSelectedRows(selectedRowKeys);
    }
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                新增
              </Button>
            )}
            {permission.check() && (
              <Button
                onClick={async () => {
                  const res = await proDataSewageDownloadTemplate({
                    skipErrorHandler: true,
                    responseType: 'blob'
                  });
                  Saver.saveAs(res?.data, '污水数据分析模板.xlsx');
                }}
                type="primary"
              >
                下载模板
              </Button>
            )}
            {permission.check() && (
              <Upload
                maxCount={1}
                accept=".xls,.xlsx"
                showUploadList={false}
                beforeUpload={() => false}
                fileList={fileList.current}
                onChange={(info) => {
                  fileList.current = info.fileList;
                  if (fileList.current.length) {
                    handleImport.run();
                  }
                }}
              >
                <Button type="primary">导入</Button>
              </Upload>
            )}
          </>
        }
      >
        <ProFormSelect
          name="xm"
          label={''}
          style={{ width: '200px' }}
          placeholder="请选择项目"
          request={async () => {
            return (store.dict['productionSite'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }));
          }}
        />
        <Filter.Item name="rq">
          <DatePicker.RangePicker placeholder={['日期', '日期']} />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>

        {selectedRows.length > 0 && permission.check() && (
          <Filter.Item>
            <Popconfirm
              title={`确定要批量删除吗？`}
              onConfirm={async () => {
                const res = await proDataSewageDelete({
                  id: selectedRows.join(',')
                });
                store.app?.message.success(res.message);
                table.refresh();
                setSelectedRows([]);
              }}
            >
              <Button type="primary" danger>
                批量删除
              </Button>
            </Popconfirm>
          </Filter.Item>
        )}
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        rowSelection={{ type: 'checkbox', ...rowSelection }}
        columns={[
          {
            title: '序号',
            dataIndex: 'index',
            align: 'center',
            render: (_, row, index) => index + 1
          },
          {
            title: '日期',
            dataIndex: 'rq',
            render: (text, row) => <div>{dayjs(text).format('YYYY-MM-DD')}</div>
          },
          { title: '项目', dataIndex: 'xm' },
          { title: '生产计划', dataIndex: 'scjh' },
          { title: '站内来水', dataIndex: 'znls' },
          { title: '厨余来水', dataIndex: 'cyls' },
          { title: '站外转运来水', dataIndex: 'zwzyls' },
          { title: '格栅进水', dataIndex: 'gsjs' },
          { title: '生化进水', dataIndex: 'shjs' },
          { title: '工艺出水', dataIndex: 'gycs' },
          { title: '预处理出渣', dataIndex: 'yclcz' },
          { title: '生化排泥', dataIndex: 'shpn' },
          { title: '化学排泥', dataIndex: 'hxpn' },
          { title: '脱水生化污泥', dataIndex: 'dsshwn' },
          { title: '脱水化学污泥', dataIndex: 'dshxwn' },
          { title: '自来水用量', dataIndex: 'zlsyl' },
          { title: '中水回用量', dataIndex: 'zshyl' },
          { title: '电量', dataIndex: 'dl' },
          { title: '一体化来水', dataIndex: 'ythls' },
          { title: '一体化进水', dataIndex: 'ythjs' },
          { title: '一体化出水', dataIndex: 'ythcs' },
          { title: '一体化排泥', dataIndex: 'ythpn' },
          { title: '污水厂剩余库容', dataIndex: 'wscsykr' },
          { title: '应急池剩余库容', dataIndex: 'yjcsykr' },
          { title: '生产异常情况说明', dataIndex: 'scycqksm' },
          { title: '进水COD', dataIndex: 'jscod' },
          { title: '进水氨氮', dataIndex: 'jshdan' },
          { title: '进水总氮', dataIndex: 'jszd' },
          { title: '出水COD', dataIndex: 'cscod' },
          { title: '出水氨氮', dataIndex: 'cshdan' },
          { title: '出水总氮', dataIndex: 'cszd' },
          { title: '出水总磷', dataIndex: 'cszp' },
          { title: '植物除臭药剂', dataIndex: 'zwccyj' },
          { title: '次氯酸钠', dataIndex: 'clsd' },
          { title: '复合型碳源液体1', dataIndex: 'fhxtyytt1' },
          { title: '复合型碳源液体2', dataIndex: 'fhxtyytt2' },
          { title: '聚氯化铝固体', dataIndex: 'jlhglgt' },
          { title: '聚氯化铝液体', dataIndex: 'jlhhlyt' },
          { title: '聚氯化铝饮用水级', dataIndex: 'jlhhlyysj' },
          { title: '浓硫酸', dataIndex: 'nls' },
          { title: '七水硫酸亚铁', dataIndex: 'qslsytt' },
          { title: '除磷剂', dataIndex: 'cpj' },
          { title: '氯酸钠', dataIndex: 'clsnd' },
          { title: '片碱', dataIndex: 'pj' },
          { title: '葡萄糖', dataIndex: 'ptj' },
          { title: '三氯化铁液体', dataIndex: 'sllhtyt' },
          { title: '稀硫酸', dataIndex: 'xls' },
          { title: '盐酸', dataIndex: 'ys' },
          { title: '阳离子聚丙烯酰胺1', dataIndex: 'ylzblxyam1' },
          { title: '阳离子聚丙烯酰胺2', dataIndex: 'ylzblxyam2' },
          { title: '液碱（32%）', dataIndex: 'yj32' },
          { title: '液碱（50%）', dataIndex: 'yj50' },
          { title: '双氧水', dataIndex: 'dyy' },
          { title: '消泡剂', dataIndex: 'xpj' },
          { title: '柠檬酸', dataIndex: 'mlss' },
          { title: '阴离子聚丙烯酰胺', dataIndex: 'ylzblxyam' },
          { title: '纳滤阻垢剂', dataIndex: 'nlfzgj' },
          { title: '膜清洗剂酸', dataIndex: 'mqxjs' },
          { title: '膜清洗剂碱', dataIndex: 'mqxjj' },
          { title: '洛碛渗滤液非氧化杀菌剂', dataIndex: 'lqslfyyxj' },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              function equDefectAcceptanceSubmit(arg0: { id: string }) {
                throw new Error('Function not implemented.');
              }

              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={() =>
                        edit.current!.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        })
                      }
                    >
                      编辑
                    </Text>
                  )}
                  {permission.check() && (
                    <Popconfirm
                      title={`确定删除该条数据吗？`}
                      onConfirm={async () => {
                        const res = await proDataSewageDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success('删除成功');
                        table.refresh();
                      }}
                    >
                      <Text>删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />

      <Spin spinning={spinning} tip="数据导入中..." size="large" fullscreen />
    </>
  );
};

export default Page;
